package com.lg.atp.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import com.lg.atp.common.Constants;
import com.lg.atp.entity.ScheduleJob;
import com.lg.atp.entity.TblAppInfo;
import com.lg.atp.entity.TblDeviceInfo;
import com.lg.atp.entity.TblTestTask;
import com.lg.atp.entity.TblTestTaskCaseRunWithBLOBs;
import com.lg.atp.service.ConfigService;
import com.lg.atp.service.IAppInfoService;
import com.lg.atp.service.ICaseService;
import com.lg.atp.service.IDeviceInfoService;
import com.lg.atp.service.ITaskCaseRunService;
import com.lg.atp.service.ITestTaskCaseService;
import com.lg.atp.service.ITestTaskDeviceService;
import com.lg.atp.service.ITestTaskService;
import com.lg.atp.service.ScriptService;
import com.lg.atp.utils.DeviceConstants;
import com.lg.atp.utils.DeviceUtil;
import com.lg.atp.utils.JobParameter;
import com.lg.atp.ws.WSClient;

/**
 * @Description: 任务执行类
 * 
 * @ClassName: QuartzJob
 * 
 */
// @Component
public class QuartzJob implements Job {

	public static QuartzJob quartzJob;
	
	private @Value("${serverIP}") String serverIP;
	private @Value("${serverPort}") Integer serverPort;
	private @Value("${relibleMasterIp}") String relibleMasterIp;

	@PostConstruct
	public void init() {
		quartzJob = this;
	}

	@Autowired
	private ITestTaskService iTestTaskService;

	@Autowired
	private ITestTaskCaseService iTestTaskCaseService;

	@Autowired
	private IAppInfoService iAppInfoService;

	@Autowired
	private ICaseService iTestCaseService;

	@Autowired
	private IDeviceInfoService deviceService;

	@Autowired
	private ITaskCaseRunService iTaskCaseRunService;

	@Autowired
	private ITestTaskDeviceService iTestTaskDeviceService;

	@Autowired
	private ScriptService scriptService;
	
	@Autowired
	private ConfigService configService;

	@Override
	public void execute(JobExecutionContext arg0) throws JobExecutionException {

		System.out.println("this is jobKey " + arg0.getTrigger().getJobKey().getName() + "✨✨✨✨✨✨✨✨");

		String jobName = arg0.getTrigger().getJobKey().getName();
		List<TblTestTask> taskList = quartzJob.iTestTaskService.selectByTaskNum(jobName);
		for (TblTestTask task : taskList) {
			System.out.println(task.getTaskNum());
			
			quartzJob.scriptService.generateScriptByTaskId(task.getId());
			List<TblTestTaskCaseRunWithBLOBs> runList = quartzJob.iTaskCaseRunService
					.selectByTaskId(task.getId());
			for(TblTestTaskCaseRunWithBLOBs run :runList){
				if (task.getAppId() != null) {
					TblAppInfo projectApp = quartzJob.iAppInfoService.selectAppById(task.getAppId());
					// 设置设备类型
					TblDeviceInfo deviceInfo = new TblDeviceInfo();
					deviceInfo = quartzJob.deviceService.geTblDeviceInfoById(run.getDeviceId());
					// 向batchSubTask保存设备类型
					String deviceTypeVo = deviceInfo.getPlatform();

					// iTaskCaseRunService.insertTaskCaseRun(batchSubTask);

					if (projectApp != null) {
						Integer platform = projectApp.getPlatform();
						String platForm = "";
						if (DeviceConstants.AUTO_APP_PLATFORM_ANDROID == platform.intValue()) {
							platForm = "android";
						} else {
							platForm = "ios";
						}

						// 检查设备的平台跟案例上选择的应用的平台是否相同，相同的才创建job
						if (!deviceInfo.getPlatform().toUpperCase().contains(platForm.toUpperCase().toString())) {
							continue;
						}


						JobParameter jobParameter = new JobParameter();

						// 设置应用类型
						jobParameter.setAppType(projectApp.getAppType());

						jobParameter.setDeviceType(deviceInfo.getDeviceType());
						jobParameter.setDeviceId(deviceInfo.getUdid());

						jobParameter.setAppUrl(
								DeviceUtil.getDemoServerAppUrl(serverIP, serverPort, Long.valueOf(task.getAppId())));

						jobParameter.setResultUrl(DeviceUtil.getDemoServerResultUrl(serverIP, serverPort, Long.valueOf(run.getCaseId()),
								Long.valueOf(run.getId())));

						jobParameter.setScriptUrl(DeviceUtil.getDemoServerScriptUrl(serverIP, serverPort, Long.valueOf(run.getScriptId())));

						jobParameter.setJobStatusUrl(DeviceUtil.getDemoJobStatusUrl(serverIP, serverPort));

						WSClient wsClient = new WSClient(DeviceUtil.getMatcServer(relibleMasterIp, 3333));
						try {
							String jobIdString = wsClient.submitJob(jobParameter);
							run.setJobId(jobIdString);
							run.setTestTaskRunStatus((long)Constants.TASK_EXCECUTION_ING);
							quartzJob.iTaskCaseRunService.updateByTaskCaseRunId(run);
							if(task.getScheduleFrequency()==1){
								List<ScheduleJob> jobList = quartzJob.configService.selectByJobName(jobName);
								for(ScheduleJob job:jobList){
									job.setJobStatus(0);
									quartzJob.configService.updateByJobId(job);
								}
								
							}
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}

				}
			}
			
		}
	}

	public static void main(String[] args) {
		Date date = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("s m H d M ? YYYY");
		String scheduleCron = dateFormat.format(date);
		System.out.println(scheduleCron);
	}
}
